import { useState } from 'react';
import { useHistory } from 'react-router-dom';
import { InputItem, Button, WingBlank, WhiteSpace, Toast } from 'antd-mobile';

import * as userApi from '../../api/user';

import './index.css';

const Login = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const history = useHistory();

    // 登录
    const handleLogin = async () => {
        console.log('username', username);
        console.log('password', password);
        const res = await userApi.login({ username, password });
        if (res.code !== 200) {
            Toast.fail(res.message);
            return;
        }
        // 将登录信息保存到 sessionStorage 中，方便 axios 请求拦截将其加到 header 中
        window.sessionStorage.setItem('token', res.data.token);
        // 跳转到地址页面
        history.push('/address');
    };

    return (
        <div className="login-page">
            <h3 className="title">登录系统</h3>

            <WingBlank>
                <InputItem
                    placeholder="请输入用户名"
                    onChange={(username) => setUsername(username)}
                />

                <WhiteSpace size="lg" />

                <InputItem
                    type="password"
                    placeholder="请输入密码"
                    onChange={(password) => setPassword(password)}
                />

                <WhiteSpace size="lg" />

                <Button onClick={handleLogin}>登录</Button>
            </WingBlank>
        </div>
    );
};

export default Login;
